package com.system.login.controller;


import com.system.login.dao.GaoyuanLoginsystemMapper;
import com.system.login.dataobject.GaoyuanLoginsystem;
import com.system.login.model.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import java.util.*;

@Controller
public class CommentPostController {

    @Autowired
    private GaoyuanLoginsystemMapper gaoyuanLoginsystemMapper;
    private Map<String, Comment> commentMap = new HashMap<>();

    private Map<String, List<Comment>> comments = new HashMap<>();
    private int i = 1;

    @RequestMapping(value = "/comment/post")
    public String post(ModelMap modelMap, @RequestParam("id") String id, Comment comment, @RequestParam(value = "name", required = false) String name, RedirectAttributesModelMap redirectAttributesModelMap) {

        Date date = new Date();
        comment.setDate(date);
        // comment.setId("12");
        //  comment.setId(UUID.randomUUID().toString());

//        ModelMap modelMap=new ModelMap();
        modelMap.addAttribute("name", name);
//        System.out.println(modelMap.get("name")+"000000");
//        redirectAttributes.addFlashAttribute("name",name);
       // System.out.println(comment.getId());
        redirectAttributesModelMap.addAttribute("name", name);

        comments.computeIfAbsent(name, k -> new ArrayList<>()).add(comment);
        List<Comment> commentList = comments.get(name);
        Collections.sort(commentList, new Comparator<Comment>() {
            @Override
            public int compare(Comment o1, Comment o2) {
                if (o1.getDate().after(o2.getDate())) {
                    return -1;
                } else {
                    return 1;
                }

            }


        });
        return "redirect:/comments";
    }

    List<Comment> getcomments(String name) {
        System.out.println(name);
        return comments.get(name);
    }
}